//
//  SMMusicPlayer.swift
//  ShareMusic
//
//  Created by 胡岩 on 16/5/4.
//  Copyright © 2016年 胡岩. All rights reserved.
//

import UIKit
import AVFoundation
import MediaPlayer
typealias Clouse = ()->()
class SMMusicPlayer: UIView {
    var startPoint:CGPoint?
    var button:UIButton?
    var effectview:UIVisualEffectView?
    var pic:UIImageView?
    var song:UILabel?
    var singer:UILabel?
    var singerImage:UIImageView?
    var lastBtn:UIButton?
    var nextBtn:UIButton?
    var startBtn:UIButton?
    var collect:UIButton?
    var order:UIButton?
    var list:UIButton?
    var download:UIButton?
    var player:AVPlayer?
    var playerItem:AVPlayerItem?
    var timer:NSTimer?
    var playingInfo:[String:AnyObject]?
    var slider:UISlider?
    var gapWidth:CGFloat = (CGRect.screenWidth() - 30 * 4) / 5.0
    var model:songModel?
    var stopTimeLength:CGFloat = 0
    var stopTimer:NSTimer?
    var clouse:Clouse?
    
    var singerInfo:SingerInfo?
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(-CGRect.screenWidth(), 0, CGRect.screenWidth(), CGRect.screenHeight()))
        self.backgroundColor = UIColor.whiteColor()
        
        let window:UIWindow = UIApplication.sharedApplication().keyWindow!
        window.addSubview(self)
        
        self.button = UIButton.init(type: UIButtonType.Custom)
        self.button?.frame = CGRectMake(0, CGRect.screenHeight() / 2.0 - 15, 30, 30)
        self.button?.setImage(UIImage.init(named: "向右"), forState: UIControlState.Normal)
        window.addSubview(self.button!)
        self.button?.addTarget(self, action: #selector(MusicList.tapButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        let blur:UIBlurEffect = UIBlurEffect.init(style: UIBlurEffectStyle.Dark)
        self.effectview = UIVisualEffectView.init(effect: blur)
        self.effectview?.frame = self.bounds;
        pic = UIImageView.init(frame: self.bounds)
        pic?.image = UIImage.init(named: "音乐")
        self.addSubview(pic!)
        pic?.addSubview(effectview!)
        
        song = UILabel.init(frame: CGRectMake(0, 40, CGRect.screenWidth(), 30))
        song?.font = UIFont .systemFontOfSize(27)
        song?.textAlignment = NSTextAlignment.Center
        song?.textColor = UIColor.whiteColor()
        self.addSubview(song!)
        
        singer = UILabel.init(frame: CGRectMake(0, (song?.frame.size.height)! + (song?.frame.origin.y)! + 15, CGRect.screenWidth(), 20))
        singer?.font = UIFont.systemFontOfSize(20)
        singer?.textAlignment = NSTextAlignment.Center
        singer?.textColor = UIColor.whiteColor()
        self.addSubview(singer!)
        
        singerImage = UIImageView.init(frame: CGRectMake(40, (singer?.frame.origin.y)! + (singer?.frame.size.height)! + 20, CGRect.screenWidth() - 80,  CGRect.screenWidth() - 80))
        singerImage?.image = UIImage.placeholdImage()
        singerImage?.layer.cornerRadius = (CGRect.screenWidth() - 80) / 2.0
        singerImage?.clipsToBounds = true
        singerImage?.contentMode = UIViewContentMode.ScaleAspectFill
        self.addSubview(singerImage!)
        
        slider = UISlider.init(frame: CGRectMake(60, (singerImage?.frame.origin.y)! + singerImage!.frame.size.height + 30, CGRect.screenWidth() - 120, 30))
        self.addSubview(slider!)
        slider?.thumbRectForBounds(CGRectMake(0, 0, 10, 10), trackRect: CGRectMake(0, 0, CGRect.screenWidth() - 120, 4), value: 0)
        slider?.setThumbImage(UIImage.init(named: "滑块"), forState: UIControlState.Normal)
        slider?.minimumTrackTintColor = UIColor.greenColor()
        slider?.addTarget(self, action: #selector(self.slidSlider), forControlEvents: UIControlEvents.ValueChanged)
        
        lastBtn = UIButton.init(type: UIButtonType.Custom)
        lastBtn?.frame = CGRectMake((CGRect.screenWidth() - 260) / 2.0, slider!.frame.origin.y + slider!.frame.size.height + 30, 40, 40)
        lastBtn?.setBackgroundImage(UIImage.init(named: "上一曲"), forState: UIControlState.Normal)
        lastBtn?.addTarget(self, action: #selector(self.last), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(lastBtn!)
        
        startBtn = UIButton.init(type: UIButtonType.Custom)
        startBtn?.frame = CGRectMake(lastBtn!.frame.origin.x + lastBtn!.frame.size.width + 60, slider!.frame.origin.y + slider!.frame.size.height + 20, 60, 60)
        startBtn?.setBackgroundImage(UIImage.init(named: "暂停"), forState: UIControlState.Normal)
        startBtn?.tag = 2
        startBtn?.addTarget(self, action: #selector(self.startOrPuase(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(startBtn!)
        
        nextBtn = UIButton.init(type: UIButtonType.Custom)
        nextBtn?.frame = CGRectMake(startBtn!.frame.origin.x + startBtn!.frame.size.width + 60, slider!.frame.origin.y + slider!.frame.size.height + 30, 40, 40)
        nextBtn?.setBackgroundImage(UIImage.init(named: "下一曲"), forState: UIControlState.Normal)
        nextBtn?.addTarget(self, action: #selector(self.next), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(nextBtn!)
        
        collect = UIButton.init(type: UIButtonType.Custom)
        collect?.frame = CGRectMake(gapWidth, lastBtn!.frame.size.height + lastBtn!.frame.origin.y + 40, 30, 30)
        collect?.setImage(UIImage.init(named: "收藏"), forState: UIControlState.Normal)
        collect?.addTarget(self, action: #selector(self.collectSong(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(collect!)
        collect?.tag = 1
        
        order = UIButton.init(type: UIButtonType.Custom)
        order?.frame = CGRectMake(gapWidth * 2 + 30, collect!.frame.origin.y, collect!.frame.size.width, collect!.frame.size.height)
        order?.setImage(UIImage.init(named: "顺序"), forState: UIControlState.Normal)
        order?.tag = 1
        order?.addTarget(self, action: #selector(self.changeOrder(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(order!)
        
        download = UIButton.init(type: UIButtonType.Custom)
        download?.frame = CGRectMake(gapWidth * 3 + 30 * 2, collect!.frame.origin.y, collect!.frame.size.width, collect!.frame.size.height)
        download?.tag = 1
        download?.setImage(UIImage.init(named: "下载"), forState: UIControlState.Normal)
        download?.addTarget(self, action: #selector(self.downloadSong(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(download!)
        
        list = UIButton.init(type: UIButtonType.Custom)
        list?.frame = CGRectMake(gapWidth * 4 + 30 * 3, collect!.frame.origin.y, collect!.frame.size.width, collect!.frame.size.height)
        list?.setImage(UIImage.init(named: "播放列表"), forState: UIControlState.Normal)
        list?.addTarget(self, action: #selector(self.showLists(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(list!)
    }
    
    func collectSong(button:UIButton) {
        let db:Database = Database.init()
        if db.haveData(self.model, type: DBType.Collect) == false {
            button.setImage(UIImage.init(named: "已收藏"), forState: UIControlState.Normal)
            db.insert(self.model, type: DBType.Collect)
        } else {
            button.setImage(UIImage.init(named: "收藏"), forState: UIControlState.Normal)
            db.delete(self.model, type: DBType.Collect)
        }
    }
    
    func changeOrder(button:UIButton) {
        if button.tag == 1 {
            button.setImage(UIImage.init(named: "随机播放"), forState: UIControlState.Normal)
            button.tag = 2
        } else if button.tag == 2 {
            button.tag = 3
            button.setImage(UIImage.init(named: "单曲循环"), forState: UIControlState.Normal)
        } else {
            button.tag = 1
            button.setImage(UIImage.init(named: "顺序"), forState: UIControlState.Normal)
        }
    }
    
    func downloadSong(button:UIButton) {
        let db:Database = Database.init()
        if db.haveData(self.model, type: DBType.Download) == false {
            Network.networkGetData((self.model?.songDetails?.url)!, model: self.model!) { (data, model) in
                button.setImage(UIImage.init(named: "已下载"), forState: UIControlState.Normal)
                let filemanager:NSFileManager = NSFileManager.defaultManager()
                filemanager.createFileAtPath( (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("\((self.model!.song_id)!).mp3"), contents: data as? NSData, attributes: nil)
                db.insert(model, type: DBType.Download)
            }
        }
    }
    
    func showLists(button:UIButton) {
        MusicList.shareInstance().open()
    }
    
    func startOrPuase(button:UIButton) {
        if button.tag == 1 {
            button.tag = 2
            button.setBackgroundImage(UIImage.init(named: "暂停"), forState: UIControlState.Normal)
            self.pause()
        } else {
            self.player?.play()
            if timer == nil {
                self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(SMMusicPlayer.turnSingerImage), userInfo: nil, repeats: true)
            }
            button.tag = 1
            button.setBackgroundImage(UIImage.init(named: "播放"), forState: UIControlState.Normal)
            if self.model == nil {
                self.play(nil)
            }
        }
    }
    
    
    func tapButton(button:UIButton) {
        if self.button!.frame.origin.x  <= 0 {
            self.open()
        } else {
            self.close()
        }
    }
    
    class func shareInstance() -> SMMusicPlayer {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: SMMusicPlayer? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SMMusicPlayer.init(frame: CGRectMake(-CGRect.screenWidth(), 0, CGRect.screenWidth(), CGRect.screenHeight()))
            let session:AVAudioSession = AVAudioSession.sharedInstance()
            do {
                try session.setCategory(AVAudioSessionCategoryPlayback)
                try session.setActive(true)
            } catch (_) {
                
            }
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SMMusicPlayer.next), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SMMusicPlayer.failPlay), name: AVPlayerItemFailedToPlayToEndTimeNotification, object: nil)
        }
        return Static.instance!
    }
    
    class func failPlay() {
        SMMusicPlayer.shareInstance().pause()
    }
    
    func next() {
        if SMMusicPlayer.shareInstance().order?.tag == 1 || SMMusicPlayer.shareInstance().order?.tag == 3 {
            if MusicList.shareInstance().lists.count - 1 > MusicList.shareInstance().currentNumberOfSongs {
                MusicList.shareInstance().currentNumberOfSongs += 1
            } else {
                MusicList.shareInstance().currentNumberOfSongs = 0
            }
        } else if SMMusicPlayer.shareInstance().order?.tag == 2 {
            if MusicList.shareInstance().lists.count > 0 {
                MusicList.shareInstance().currentNumberOfSongs = Int(arc4random()) % (MusicList.shareInstance().lists.count - 1)
            } else {
                MusicList.shareInstance().currentNumberOfSongs = 0
            }
        }
        MusicList.shareInstance().playCurrentSong()
    }
    
    class func next() {
        if SMMusicPlayer.shareInstance().order?.tag == 1 {
            if MusicList.shareInstance().lists.count - 1 > MusicList.shareInstance().currentNumberOfSongs {
                MusicList.shareInstance().currentNumberOfSongs += 1
            } else {
                MusicList.shareInstance().currentNumberOfSongs = 0
            }
        } else if SMMusicPlayer.shareInstance().order?.tag == 2 {
            if MusicList.shareInstance().lists.count > 0 {
                MusicList.shareInstance().currentNumberOfSongs = Int(arc4random()) % (MusicList.shareInstance().lists.count - 1)
            } else {
                MusicList.shareInstance().currentNumberOfSongs = 0
            }
        }
        MusicList.shareInstance().playCurrentSong()
    }
    
    func last() {
        if MusicList.shareInstance().currentNumberOfSongs > 0 {
            MusicList.shareInstance().currentNumberOfSongs -= 1
        } else {
            MusicList.shareInstance().currentNumberOfSongs = MusicList.shareInstance().lists.count  > 0 ? MusicList.shareInstance().lists.count - 1 : 0
        }
        MusicList.shareInstance().playCurrentSong()
    }
    
    func close() {
        UIView.animateWithDuration(0.4) {
            self.frame = CGRectMake(-CGRect.screenWidth(), 0, CGRect.screenWidth(), CGRect.screenHeight())
            self.button?.frame = CGRectMake(0, CGRect.screenHeight() / 2.0 - 15, 30, 30)
            self.button?.setImage(UIImage.init(named: "向右"), forState: UIControlState.Normal)
        }
    }
    
    func open() {
        UIView.animateWithDuration(0.4) {
            self.frame = CGRectMake(0, 0, CGRect.screenWidth(), CGRect.screenHeight())
            self.button?.frame = CGRectMake(CGRect.screenWidth() - 30, CGRect.screenHeight() / 2.0 - 15, 30, 30)
            self.button?.setImage(UIImage.init(named: "向左"), forState: UIControlState.Normal)
        }
        let window:UIWindow = UIApplication.sharedApplication().keyWindow!
        window.bringSubviewToFront(self)
        window.bringSubviewToFront(button!)
        if self.clouse != nil {
            self.clouse!()
        }
    }
    
    func openClouse(clouse: ()->()){
        self.clouse = clouse
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        let touch = (touches as NSSet).anyObject()
        self.startPoint = (touch as! UITouch).locationInView(self.superview)
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesMoved(touches, withEvent: event)
        let touch = (touches as NSSet).anyObject()
        let movePoint = (touch as! UITouch).locationInView(self.superview)
        let x = movePoint.x - (self.startPoint?.x)! + self.frame.size.width / 2.0
        if x <= self.frame.size.width / 2.0 {
            self.center = CGPointMake(x, self.frame.size.height / 2.0)
            self.button?.center = CGPointMake(x + 15 + self.frame.size.width / 2.0, CGRect.screenHeight() / 2.0 - 15)
        } else {
            self.open()
        }
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesEnded(touches, withEvent: event)
        let touch = (touches as NSSet).anyObject()
        let endPoint = (touch as! UITouch).locationInView(self.superview)
        let previousPoint = (touch as! UITouch).previousLocationInView(self.superview)
        if endPoint.x - previousPoint.x > -1.5 {
            self.open()
        } else {
            self.close()
        }
    }
    
    func play(model:songModel?) {
        if model != nil {
            self.model = model
        }
        if self.model == nil {
            if MusicList.shareInstance().lists.count > 0 {
                self.model = MusicList.shareInstance().lists[0] as? songModel
                MusicList.shareInstance().currentNumberOfSongs = 0
            }
        }
        startBtn?.tag = 1
        startBtn?.setBackgroundImage(UIImage.init(named: "播放"), forState: UIControlState.Normal)
        if self.model != nil {
            self.checkDownloadOrCollect(true, model: self.model!)
            self.checkDownloadOrCollect(false, model: self.model!)
            if self.model?.type == 1 {
                playerItem = AVPlayerItem.init(URL:  NSURL.init(string: self.model!.songDetails!.url!)!)
            } else {
                playerItem = AVPlayerItem.init(URL: NSURL.init(fileURLWithPath: (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("\((self.model!.song_id)!).mp3")))
                print((NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("\((self.model!.song_id)!).mp3"))
            }
            player = AVPlayer.init(playerItem: playerItem!)
        }
        player?.play()
        if self.model != nil {
            self.getSingerInfo(((self.model?.singer_id!)?.integerValue)!, song: (self.model?.song_name)!)
        }
        if timer == nil {
            self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(SMMusicPlayer.turnSingerImage), userInfo: nil, repeats: true)
        }
    }
    
    func checkDownloadOrCollect(download:Bool, model:songModel) {
        if download == true {
            let db:Database = Database.init()
            if db.haveData(model, type: DBType.Download) == true {
                self.download?.setImage(UIImage.init(named: "已下载"), forState: UIControlState.Normal)
            } else {
                self.download?.setImage(UIImage.init(named: "下载"), forState: UIControlState.Normal)
            }
        } else {
            let db:Database = Database.init()
            if db.haveData(model, type: DBType.Collect) == true {
                self.collect?.setImage(UIImage.init(named: "已收藏"), forState: UIControlState.Normal)
            } else {
                self.collect?.setImage(UIImage.init(named: "收藏"), forState: UIControlState.Normal)
            }
        }
    }
    
    func turnSingerImage() {
        UIView.animateWithDuration(1.5) {
            self.singerImage?.transform = CGAffineTransformRotate(self.singerImage!.transform, CGFloat(M_PI) / 27.0)
        }
        if playerItem?.duration.seconds.isNaN == false {
            slider?.maximumValue = Float((playerItem?.duration.seconds)!)
            slider?.value = Float((playerItem?.currentTime().seconds)!)
        }
    }
    
    func slidSlider() {
        if playerItem?.duration.seconds.isNaN == false {
            playerItem?.seekToTime(CMTime.init(seconds: Double(slider!.value), preferredTimescale: 1))
        }
    }

    func pause() {
        startBtn?.tag = 2
        startBtn?.setBackgroundImage(UIImage.init(named: "暂停"), forState: UIControlState.Normal)
        player?.pause()
        self.timer?.invalidate()
        self.timer = nil
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getSingerInfo(singerId:Int, song:String) {
        self.singer?.text = self.model?.singer_name
        self.song?.text = song
        self.playingInfo = [MPMediaItemPropertyTitle:song]
        self.playingInfo?.updateValue(song, forKey: MPMediaItemPropertyTitle)
        self.playingInfo?.updateValue((self.model?.singer_name)!, forKey: MPMediaItemPropertyArtist)
        self.playingInfo?.updateValue(MPMediaItemArtwork.init(image: (self.pic?.image)!), forKey: MPMediaItemPropertyArtwork)
        MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = self.playingInfo!
        Network.networkGet(URLs.singerInfoUrl.stringByAppendingFormat("/%d?detail=true&app=ttpod&v=v7.9.4.2015052918&uid=&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.1.3&active=1&net=2&openudid=79792c08a7dfa63c2a951b75a564d02258847fe0&idfa=5A4BDB8F-1B62-4935-BB75-F371FD524202&utdid=VXQOrj7lpYoDAEssqhP8uWqW&alf=201200&bundle_id=com.ttpod.music", singerId)) { (json) in
            if json["code"] as! Int == 1 {
                self.singerInfo = SingerInfo.init(dic: json["data"] as! [String:AnyObject]?)
                self.pic?.sd_setImageWithURL(NSURL.init(string: self.singerInfo?.picUrl == nil ? "":(self.singerInfo?.picUrl)!), placeholderImage: UIImage.placeholdImage())
                self.singerImage?.sd_setImageWithURL(NSURL.init(string: self.singerInfo?.picUrl == nil ? "":(self.singerInfo?.picUrl)!), placeholderImage: UIImage.placeholdImage())
                dispatch_async(dispatch_get_global_queue(0, 0), {
                    repeat {
                        if self.playerItem?.duration.seconds >= 0 {
                            dispatch_async(dispatch_get_main_queue(), { 
                                self.playingInfo = [MPMediaItemPropertyTitle:song]
                                self.playingInfo?.updateValue(song, forKey: MPMediaItemPropertyTitle)
                                self.playingInfo?.updateValue((self.singerInfo?.name)!, forKey: MPMediaItemPropertyArtist)
                                self.playingInfo?.updateValue(MPMediaItemArtwork.init(image: (self.pic?.image)!), forKey: MPMediaItemPropertyArtwork)
                                self.playingInfo?.updateValue((self.playerItem?.duration.seconds)!, forKey: MPMediaItemPropertyPlaybackDuration)
                                self.playingInfo?.updateValue((self.playerItem?.currentTime().seconds)!, forKey: MPNowPlayingInfoPropertyElapsedPlaybackTime)
                                MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = self.playingInfo!
                            })
                        }
                    } while ((self.playerItem?.duration.seconds.isNaN)! == true) || ((self.playerItem?.currentTime().seconds)! == 0.5)
                })
            }
        }
    }
    
    func startStopTimer(second: Double) {
        stopTimer?.invalidate()
        if second > 0 {
            stopTimer = NSTimer.scheduledTimerWithTimeInterval(second, target: self, selector: #selector(self.pause), userInfo: nil, repeats: false)
        }
    }
    
}
